package films;

import java.io.*;

public class Test {

	protected String ruta;
	
	public static void main( String [] args ) {
		(new Test()).run();
	}
	
	public Test() { 
		ruta = "pelis.dat";
	}
	
	public void run(){
		iniciar();
		mostrar();
		System.out.println("Se elimina The Godfather");
		eliminar();
		mostrar();
	}
	
	public void iniciar(){
		Film theGodfather=new Film("The Godfather", "10", "Muy buena");
		Film meanStrets=new Film("Mean Streets", "7", "Buena");
		Film ParanormalActivity2=new Film("Paranormal Activity 2", "2", "Mala");		
		FilmsCollection films=new FilmsCollection();		
		films.put(theGodfather);
		films.put(meanStrets);
		films.put(ParanormalActivity2);
			
		grabar(films);
	}
	
	public FilmsCollection recuperar(){
		FilmsCollection films=null;
		try {
			// Abrir archivo y recuperar mapeo:
			File file = new File( ruta);
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(ruta));
			films=(FilmsCollection) in.readObject();
			in.close();			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return films;
	}
	
	public void grabar(FilmsCollection films){
		try {
			File file =new File(ruta);
			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(ruta));
			out.writeObject( films );
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void mostrar(){
		FilmsCollection films=recuperar();
		for (Film f:films.films())
			System.out.println(f.getTitle());
	}
	
	public void eliminar(){
		FilmsCollection films=recuperar();
		//Eliminacion
		films.remove("The Godfather");
		grabar(films);		
	}

}
